package com.datastructure.test.dynamic.maxlengthofbackstring;

public class MaxLengthOfBackString {

    public static void main(String[] args) {
        MaxLengthOfBackString maxLengthOfBackString = new MaxLengthOfBackString();
        String data = "bb";
        System.out.println(maxLengthOfBackString.getMaxLengthOfBackString(data));
    }

    public int getMaxLengthOfBackString(String A){
        if(A.length()==2){
            if(A.charAt(0)==A.charAt(1)){
                return 2;
            } else {
                return 1;
            }
        }
        if(A.length()==0||A.length()==1){
            return A.length();
        }
        String s2 = reverseString(A);
        int maxLength = 0;
        int j ;
        for (int i = 0; i < A.length(); i++) {
            j = A.length();
            while (j>=i){
                String compare = A.substring(i,j);
                if(s2.contains(compare)&&isRuler(compare)){
                    maxLength = Math.max(maxLength,compare.length());
                }
                j--;
            }
        }
        return maxLength;
    }

    public boolean isRuler(String data){
        boolean result = true;
        for (int i = 0; i < data.length(); i++) {
            if(data.charAt(i)!=data.charAt(data.length()-i-1)){
                result = false;
                break;
            }
        }
        return result;
    }

    public String reverseString(String data){
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = data.length()-1;i>=0;i--){
            stringBuilder.append(data.charAt(i));
        }
        return stringBuilder.toString();
    }

    public int getLongestPalindrome (String A) {
        // write code here
        if(A.length()<2){
            return A.length();
        }
        if(A.length()==2){
            if (A.charAt(0)==A.charAt(1)){
                return 2;
            }
            return 1;
        }
        int left = 0;
        int right = 0;
        int  max = 1;
        //奇数
        for(int i = 0;i <A.length();i++){
            left = i-1;right=i+1;
            int temp = 1;
            while(left>-1&&right<A.length()&&A.charAt(left)==A.charAt(right)){
                temp+=2;
                left--;
                right++;
            }
            max=max<temp?temp:max;
        }
        //偶数
        for(int i = 0;i <A.length();i++){
            left = i-1;right=i+2;
            int temp = 2;
            int count = 0;  //若一次都进入判断 将temp清空初始值
            while(left>-1&&right<A.length()&&A.charAt(left)==A.charAt(right)&&A.charAt(i)==A.charAt(i+1)){
                count++;
                temp+=2;
                max=max<temp?temp:max;
                left--;
                right++;
            }
            if (count<1){
                temp=1;
            }
            max=max<temp?temp:max;
        }
        return max;
    }
}
